<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="86px">
      <el-form-item label="医生名" prop="doctorId">
        <el-select v-model="queryParams.doctorId" placeholder="请选择医生" clearable>
          <el-option v-for="item in doctorList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="关联话题" prop="topicId">
        <el-select v-model="queryParams.topicId" placeholder="请选择话题" clearable>
          <el-option v-for="item in topicList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['knowledge:article:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['knowledge:article:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['knowledge:article:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['knowledge:article:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="articleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="文章ID" align="center" prop="id" />
      <el-table-column label="文章标题" align="center" prop="title" />
      <!-- 文章内容列修改：先去除HTML标签，再处理溢出 -->
      <el-table-column label="文章内容" align="center">
        <template slot-scope="scope">
          <div class="article-content-text">
            {{ stripHtmlTags(scope.row.content) }}
          </div>
        </template>
      </el-table-column>
      <!-- 发布医生（显示姓名） -->
      <el-table-column label="发布医生" align="center">
        <template slot-scope="scope">
          <!-- 空值保护：避免对象为null时报错 -->
          {{ scope.row.doctor && scope.row.doctor.name }}
        </template>
      </el-table-column>
      <!-- 文章图片列 - 显示图片而非文本 -->
      <el-table-column label="文章图片" align="center">
        <template slot-scope="scope">
          <el-image v-if="scope.row.url" :src="scope.row.url" style="width: 100px; height: 100px; object-fit: contain"
            :preview-src-list="[scope.row.url]" lazy></el-image>
          <span v-else>无图片</span>
        </template>
      </el-table-column>
      <el-table-column label="发布时间" align="center" prop="time" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.time, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="阅读量" align="center" prop="readCount" />
      <el-table-column label="收藏量" align="center" prop="collectCount" />
      <el-table-column label="点赞量" align="center" prop="approve" />
      <!-- 关联话题（显示名称） -->
      <el-table-column label="关联话题" align="center">
        <template slot-scope="scope">
          {{ scope.row.topic && scope.row.topic.name }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['knowledge:article:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['knowledge:article:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改文章管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="92px">
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入文章标题" />
        </el-form-item>
        <el-form-item label="文章内容">
          <editor v-model="form.content" :min-height="192" />
        </el-form-item>
        <!-- 发布医生：编辑显名称，新增输 ID -->
        <el-form-item label="医生名" prop="doctorId">
          <el-select v-model="form.doctorId" placeholder="请选择医生" clearable>
            <el-option v-for="item in doctorList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <!-- 文章图片上传组件 -->
        <el-form-item label="文章图片" prop="url">
          <el-upload class="avatar-uploader" :action="uploadUrl" :headers="uploadHeaders" :show-file-list="true"
            :on-success="handleUploadSuccess" :on-error="handleUploadError" :before-upload="beforeUpload"
            :file-list="fileList" list-type="picture">
            <img v-if="form.url" :src="form.url" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <div style="margin-top: 10px; font-size: 12px; color: #606266;">
            提示：支持JPG、PNG格式，大小不超过2MB
          </div>
        </el-form-item>
        <el-form-item label="发布时间" prop="time">
          <el-date-picker clearable v-model="form.time" type="date" value-format="yyyy-MM-dd" placeholder="请选择发布时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="关联话题" prop="topicId">
          <el-select v-model="form.topicId" placeholder="请选择话题" clearable>
            <el-option v-for="item in topicList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listArticle,
    getArticle,
    delArticle,
    addArticle,
    updateArticle,
    listDoctor,
    listTopic
  } from "@/api/knowledge/article";
  import {
    getToken
  } from "@/utils/auth";

  export default {
    name: "Article",
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 文章管理表格数据
        articleList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          title: null,
          doctorId: null,
          readCount: null,
          collectCount: null,
          approve: null,
          topicId: null,
        },
        // 医生列表
        doctorList: [],
        // 话题列表
        topicList: [],
        // 表单参数
        form: {},
        // 上传相关配置
        uploadUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传接口地址，使用RuoYi默认的上传接口
        uploadHeaders: {
          Authorization: "Bearer " + getToken(), // 上传携带token
        },
        fileList: [], // 上传文件列表
        // 表单校验
        rules: {
          title: [{
            required: true,
            message: "文章标题不能为空",
            trigger: "blur",
          }, ],
          content: [{
            required: true,
            message: "文章内容不能为空",
            trigger: "blur",
          }, ],
          doctorId: [{
            required: true,
            message: "发布医生不能为空",
            trigger: "blur",
          }, ],
          url: [{
            required: true,
            message: "请上传文章图片",
            trigger: "change",
          }, ],
          time: [{
            required: true,
            message: "发布时间不能为空",
            trigger: "blur",
          }, ],
          topicId: [{
            required: true,
            message: "关联话题不能为空",
            trigger: "blur",
          }, ],
        },
      };
    },
    created() {
      this.getList();
      this.getDoctorList();
      this.getTopicList();
    },
    methods: {
      /** 查询文章管理列表 */
      getList() {
        this.loading = true;
        listArticle(this.queryParams).then((response) => {
          console.log("文章列表数据", response.rows);
          this.articleList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      /** 查询医生列表 */
      getDoctorList() {
        listDoctor({
          pageNum: 1,
          pageSize: 9999,
        }).then((res) => {
          if (res.code === 200) {
            this.doctorList = res.rows;
          }
        });
      },
      /** 查询话题列表 */
      getTopicList() {
        listTopic().then((res) => {
          if (res.code === 200) {
            this.topicList = res.rows;
          }
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          title: null,
          content: null,
          doctorId: null,
          url: null,
          time: null,
          readCount: null,
          collectCount: null,
          approve: null,
          topicId: null,
          del: null,
        };
        this.fileList = []; // 清空文件列表
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map((item) => item.id);
        this.single = selection.length !== 1;
        this.multiple = !selection.length;
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加文章管理";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids;
        getArticle(id).then((response) => {
          this.form = response.data;
          // 如果有图片，初始化文件列表
          if (this.form.url) {
            this.fileList = [{
              name: "article-image",
              url: this.form.url,
            }, ];
          }
          this.open = true;
          this.title = "修改文章管理";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate((valid) => {
          if (valid) {
            if (this.form.id != null) {
              updateArticle(this.form).then((response) => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addArticle(this.form).then((response) => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除文章管理编号为"' + ids + '"的数据项？').then(function() {
          return delArticle(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download(
          "knowledge/article/export", {
            ...this.queryParams,
          },
          `article_${new Date().getTime()}.xlsx`
        );
      },
      /** 上传成功处理 */
      handleUploadSuccess(response, file, fileList) {
        if (response.code === 200) {
          this.form.url = response.url; // 将上传成功的图片地址赋值给表单
          this.fileList = fileList; // 更新文件列表
          this.$modal.msgSuccess("上传成功");
        } else {
          this.$modal.msgError(response.msg || "上传失败");
        }
      },
      /** 上传失败处理 */
      handleUploadError(err) {
        this.$modal.msgError("上传失败，请重试");
      },
      /** 上传前校验 */
      beforeUpload(file) {
        // 校验文件类型
        const isJPG = file.type === "image/jpeg" || file.type === "image/png";
        if (!isJPG) {
          this.$modal.msgError("只能上传JPG/PNG格式的图片");
          return false;
        }
        // 校验文件大小
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
          this.$modal.msgError("图片大小不能超过2MB");
          return false;
        }
        return true;
      },
      // 新增：去除HTML标签的工具函数
      stripHtmlTags(html) {
        if (!html) return "";
        const tempDiv = document.createElement("div");
        tempDiv.innerHTML = html;
        return tempDiv.textContent || tempDiv.innerText;
      },
    },
  };
</script>

<style scoped>
  /* 图片上传样式 */
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 150px;
    height: 150px;
    line-height: 150px;
    text-align: center;
  }

  .avatar {
    width: 150px;
    height: 150px;
    display: block;
    object-fit: contain;
  }

  /* 文章内容溢出控制样式 */
  .article-content-text {
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 3;

  }
</style>
